package com.xms.web.framework.config;

import com.xms.core.exception.XmsUnauthorizedException;
import com.xms.core.module.ModuleCollection;
import com.xms.dependency.XmsDependencyException;
import com.xms.logging.service.IAppLogging;
import com.xms.utils.StringUtil;
import com.xms.web.framework.model.JsonResultObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 全局异常处理
 * </p>
 *
 * @author migo
 * @since 2021/10/10
 */
@ControllerAdvice(basePackages = {"com.**.api.*"}, annotations = {Controller.class, RestController.class})
public class SpringExceptionHandler {
    private IAppLogging _appLogging;

    @Autowired
    public SpringExceptionHandler(IAppLogging appLogging){
        _appLogging = appLogging;
    }

    @ExceptionHandler(value=Exception.class)
    @ResponseBody
    public JsonResultObject unknownException(Exception ex) {
        ex.printStackTrace();
        _appLogging.error(ex);
        String msg = StringUtil.isEmpty(ex.getMessage()) ? ex.toString() : ex.getMessage();
        return JsonResultObject.failure(msg);
    }

    @ExceptionHandler(value= XmsDependencyException.class)
    @ResponseBody
    public JsonResultObject dependencyException(XmsDependencyException ex) {
        ex.printStackTrace();
        if(ex.dependents != null){
            ex.dependents.forEach(x->{
                x.componentTypeName = ModuleCollection.getName(x.componentType);
                x.componentLocalizedName = ModuleCollection.getLocalizedName(x.componentType);
            });
        }
        JsonResultObject result = JsonResultObject.failure(StringUtil.isEmpty(ex.getMessage()) ? ex.toString() : ex.getMessage(), ex.dependents);
        result.StatusCode = XmsDependencyException.STATUS_CODE;
        return result;
    }

    @ExceptionHandler(value= XmsUnauthorizedException.class)
    @ResponseBody
    public JsonResultObject unauthorizedException(XmsUnauthorizedException ex) {
        ex.printStackTrace();
        JsonResultObject result =  JsonResultObject.failure(StringUtil.isEmpty(ex.getMessage()) ? ex.toString() : ex.getMessage());
        result.StatusCode = 401;
        return result;
    }
}
